package com.pinyoumei.app.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.adapter.ShareQrCodeAdapter;
import com.pinyoumei.app.adapter.ShareQrCodeAdapter2;
import com.pinyoumei.app.bean.ShareCodeBean;
import com.pinyoumei.app.bean.ShareThirdBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.OnResponseListener;
import com.pinyoumei.app.utils.QRCodeUtil;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.WXShare;
import com.pinyoumei.app.view.LoadingDailog;
import com.pinyoumei.app.view.dialog.ShareWxDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2021-08-13.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-13        Administrator             新增Person类
 * 2021-08-13        Administrator             增加sex属性
 */
public class ShareQrCodeFragment extends BaseLazyLoadFragment {

    private Gson gson;
    private ArrayList<ShareThirdBean> shareThirdBeans = new ArrayList<>();
    private ArrayList<ShareThirdBean> shareThirdBeans2 = new ArrayList<>();
    private LoadingDailog loadingDailog;
    private ShareQrCodeAdapter shareQrCodeAdapter;
    private ShareQrCodeAdapter2 shareQrCodeAdapter2;
    private String codeUrl = "";
    private String img = "";
    private String code = "";
    private String name = "";

    private View imgView;
    private ImgHandler imgHandler = new ImgHandler();
    private WXShare wxShare;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_qrcode;
    }

    @Override
    public void initView(View rootView) {
        LoadingDailog.Builder builder = new LoadingDailog.Builder(getActivity())
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();
        gson = new Gson();
        wxShare = new WXShare(getActivity());
        wxShare.setListener(new OnResponseListener() {
            @Override
            public void onSuccess() {
                //分享成功
                ToastUtils.showShort("分享成功");
            }

            @Override
            public void onCancel() {
                //分享取消
                ToastUtils.showShort("分享取消");
            }

            @Override
            public void onFail(String message) {
                //分享失败
                ToastUtils.showShort("分享失败");
            }
        });

        RecyclerView recycle = rootView.findViewById(R.id.recycle);
        recycle.setLayoutManager(new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false));
        shareQrCodeAdapter = new ShareQrCodeAdapter(R.layout.item_share_code, null);
        shareQrCodeAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        recycle.setAdapter(shareQrCodeAdapter);

        shareQrCodeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
               String currentImgUrl = shareQrCodeAdapter.getData().get(position).getImg_list();
//                recycleAdapter.notifyDataSetChanged();

                ShareWxDialog shareWxDialog = new ShareWxDialog(getActivity(),currentImgUrl);
                shareWxDialog.show();

                shareWxDialog.setOnClickListener(new ShareWxDialog.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (view.getId()) {
                            case R.id.source_download:
                                //                下载图片
                                getViewByBgUrl(currentImgUrl, false, false);
                                break;
                            case R.id.source_wechat:
                                //微信
                                getViewByBgUrl(currentImgUrl, true, true);
                                break;

                            case R.id.source_friend_circle:
                                //朋友圈
                                getViewByBgUrl(currentImgUrl, true, false);
                                break;

                            default:
                                break;
                        }
                    }
                });
            }
        });


        RecyclerView recycle2 = rootView.findViewById(R.id.recycle2);
        recycle2.setLayoutManager(new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false));
        shareQrCodeAdapter2 = new ShareQrCodeAdapter2(R.layout.item_share_code2, null);
        shareQrCodeAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        recycle2.setAdapter(shareQrCodeAdapter2);

        shareQrCodeAdapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String currentImgUrl = shareQrCodeAdapter2.getData().get(position).getImg_list();
//                recycleAdapter.notifyDataSetChanged();

                ShareWxDialog shareWxDialog = new ShareWxDialog(getActivity(),currentImgUrl);
                shareWxDialog.show();

                shareWxDialog.setOnClickListener(new ShareWxDialog.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (view.getId()) {
                            case R.id.source_download:
                                //                下载图片
                                getViewByBgUrl(currentImgUrl, false, false);
                                break;
                            case R.id.source_wechat:
                                //微信
                                getViewByBgUrl(currentImgUrl, true, true);
                                break;

                            case R.id.source_friend_circle:
                                //朋友圈
                                getViewByBgUrl(currentImgUrl, true, false);
                                break;

                            default:
                                break;
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onFragmentFirst() {
        super.onFragmentFirst();

        InitData();
    }

    private void InitData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));

        OkGo.<String>post(Constants.INVITE_QRCODE)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {




                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        ShareCodeBean shareCodeBean = gson.fromJson(response.body(), ShareCodeBean.class);

                        if (shareCodeBean.getCode() >= 0) {
                            name = shareCodeBean.getResult().getImg_bottom_info().getUser_nick_name();
                            code = shareCodeBean.getResult().getImg_bottom_info().getRecommand_code();
                            img = shareCodeBean.getResult().getImg_bottom_info().getUser_head_img();
                            codeUrl = shareCodeBean.getResult().getImg_bottom_info().getQr_code_url();
                            if (shareCodeBean.getResult().getImg_list()!=null && shareCodeBean.getResult().getImg_list().size()>0){
                                for (int i = 0; i < shareCodeBean.getResult().getImg_list().size(); i++) {
                                    if (i<=1){
                                          ShareThirdBean shareThirdBean = new ShareThirdBean();
                                          shareThirdBean.setImg_list(shareCodeBean.getResult().getImg_list().get(i));
                                            shareThirdBean.setQr_code_url(shareCodeBean.getResult().getImg_bottom_info().getQr_code_url());
                                            shareThirdBean.setRecommand_code(shareCodeBean.getResult().getImg_bottom_info().getRecommand_code());
                                        shareThirdBean.setUser_head_img(shareCodeBean.getResult().getImg_bottom_info().getUser_head_img());
                                        shareThirdBean.setUser_name(shareCodeBean.getResult().getImg_bottom_info().getUser_name());
                                        shareThirdBean.setUser_nick_name(shareCodeBean.getResult().getImg_bottom_info().getUser_nick_name());
                                        shareThirdBeans.add(shareThirdBean);

                                    }else{
                                        ShareThirdBean shareThirdBean = new ShareThirdBean();
                                        shareThirdBean.setImg_list(shareCodeBean.getResult().getImg_list().get(i));
                                        shareThirdBean.setQr_code_url(shareCodeBean.getResult().getImg_bottom_info().getQr_code_url());
                                        shareThirdBean.setRecommand_code(shareCodeBean.getResult().getImg_bottom_info().getRecommand_code());
                                        shareThirdBean.setUser_head_img(shareCodeBean.getResult().getImg_bottom_info().getUser_head_img());
                                        shareThirdBean.setUser_name(shareCodeBean.getResult().getImg_bottom_info().getUser_name());
                                        shareThirdBean.setUser_nick_name(shareCodeBean.getResult().getImg_bottom_info().getUser_nick_name());
                                        shareThirdBeans2.add(shareThirdBean);

                                    }
                                }
                                shareQrCodeAdapter.setNewData(shareThirdBeans);
                                shareQrCodeAdapter2.setNewData(shareThirdBeans2);
                            }
                        } else {
                            Toast.makeText(getActivity(), shareCodeBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }
    private View getViewByBgUrl(String bgUrl, boolean isShare, boolean isFriend) {
        loadingDailog.show();
        LayoutInflater from = LayoutInflater.from(getActivity());
        WindowManager manager = getActivity().getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        int height = outMetrics.heightPixels;
        View viewById = from.inflate(R.layout.share_friend_big, null);

        LinearLayout ll_poster = viewById.findViewById(R.id.rootview);
        viewById.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        viewById.layout(0, 0, viewById.getMeasuredWidth(), viewById.getMeasuredHeight());
        ImageView codeIv = viewById.findViewById(R.id.code_iv);
        ImageView userIv = viewById.findViewById(R.id.user_iv);
        TextView codeTv = viewById.findViewById(R.id.code_tv);
        TextView userTv = viewById.findViewById(R.id.user_tv);

        ImageView iv = viewById.findViewById(R.id.iv);
        Glide.with(getActivity()).load(bgUrl).listener(new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                ToastUtils.showLong("保存失败");
                return false;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                Glide.with(getActivity()).load(img).listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        ToastUtils.showLong("保存失败");
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
                        params.width = width;
                        params.height = height;
                        params.gravity = Gravity.CENTER;
                        ll_poster.setLayoutParams(params);
                        codeIv.setImageBitmap(QRCodeUtil.createQRImage(codeUrl, width, height, null, null));

                        viewById.setDrawingCacheEnabled(true);
                        viewById.buildDrawingCache();
                        // 2. 将布局转成bitmap
                        getBitmapByView(viewById);
                        imgView = viewById;
                        if (isShare)
                            if (isFriend)
                                imgHandler.sendEmptyMessage(300);
                            else
                                imgHandler.sendEmptyMessage(400);

                        else
                            imgHandler.sendEmptyMessage(200);

                        return false;
                    }
                }).into(userIv);

                return false;
            }
        }).into(iv);
        Glide.with(getActivity()).load(img).into(userIv);
        codeIv.setImageBitmap(QRCodeUtil.createQRImage(codeUrl, width, height, null, null));
        codeTv.setText(code);
        userTv.setText(name);

        return viewById;
    }

    private Bitmap getBitmapByView(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        int width = view.getMeasuredWidth();
        int height = view.getMeasuredHeight();
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        Bitmap bp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bp);
        view.draw(canvas);
        canvas.save();
        return bp;
    }

    private void saveViewBitmap(View view) {
        Bitmap bitmap = Bitmap.createBitmap(getBitmapByView(view));
        view.setDrawingCacheEnabled(false);
        view.destroyDrawingCache();
        //3.bitmap存本地
        String strPath = "/testSaveView/" + UUID.randomUUID().toString() + ".png";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sdCardDir = Environment.getExternalStorageDirectory();
            FileOutputStream fos = null;
            try {
                File file = new File(sdCardDir, strPath);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                fos = new FileOutputStream(file);

                //当指定压缩格式为PNG时保存下来的图片显示正常
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                //当指定压缩格式为JPEG时保存下来的图片背景为黑色
//				 bitmap.compress(CompressFormat.JPEG, 100, fos);
                fos.flush();
                ToastUtils.showLong("保存成功");
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                loadingDailog.dismiss();
               getActivity().sendBroadcast(intent);
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.showLong("保存失败");
            } finally {
                try {
                    fos.close();
                    if (!bitmap.isRecycled()) {
                        bitmap.recycle();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    class ImgHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 200:
                    //下载
                    saveViewBitmap(imgView);
                    break;
                case 300:
                    //好友
                    wxShare.sharePicture(getBitmapByView(imgView), 0);
                    loadingDailog.dismiss();
                    break;
                case 400:
                    //朋友圈
                    wxShare.sharePicture(getBitmapByView(imgView), 1);
                    loadingDailog.dismiss();
                    break;
            }
        }
    }
}
